use tauri_plugin_store::StoreExt;

pub mod sources;
pub mod sources_categories;
pub mod utils;
pub mod videos;

use utils::Video;

#[tauri::command]
fn save_history(app_handle: tauri::AppHandle, video: Video) {
    let store = app_handle.store(".history.dat").unwrap();
    let json_value = store
        .get("history")
        .unwrap_or(serde_json::value::Value::Array(Vec::new()));
    let videos: Vec<Video> = serde_json::from_value::<Vec<Video>>(json_value).unwrap();
    store.set(
        "history",
        serde_json::json!(std::iter::once(&video)
            .chain(videos.iter())
            .cloned()
            .collect::<Vec<Video>>()),
    );
    let _ = store.save();
}

pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_store::Builder::new().build())
        .plugin(
            tauri_plugin_log::Builder::new()
                .timezone_strategy(tauri_plugin_log::TimezoneStrategy::UseLocal)
                .targets([
                    tauri_plugin_log::Target::new(tauri_plugin_log::TargetKind::Stdout),
                    tauri_plugin_log::Target::new(tauri_plugin_log::TargetKind::LogDir {
                        file_name: Some(chrono::Local::now().format("%Y%m%dT%H%M%S").to_string()),
                    }),
                ])
                .build(),
        )
        .setup(|app| {
            log::info!("Setup");
            tauri::WebviewWindowBuilder::new(
                app,
                "main",
                tauri::WebviewUrl::App("gui.html".into()),
            )
            .title("英语视频")
            .build()?;
            // println!(
            //     "{:?}",
            //     tauri_plugin_store::resolve_store_path(app.handle(), "history.dat")
            // );
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            sources_categories::get_sources,
            sources_categories::get_categories,
            videos::get_videos,
            save_history,
        ])
        .build(tauri::generate_context!())
        .expect("error while running tauri application")
        .run(|_, event| match event {
            tauri::RunEvent::ExitRequested { .. } => {
                log::info!("Exit requested")
            }
            tauri::RunEvent::Exit => {
                log::info!("Exit")
            }
            _ => {}
        });
}
